import { Flexbox } from "react-layout-kit";
import { useState, useEffect } from "react";
import AgentSetup from "./AgentSetup";
import { Badge, message } from "antd";
import * as signalR from "@microsoft/signalr";
import Divider from "@lobehub/ui/es/Form/components/FormDivider";
import { Tooltip } from "@lobehub/ui";
import UserAvatar from "../../components/AgentAvatar";
import AgentChat from "./AgentChat";
import AgentConsole from "./AgentConsole";
import SelectModel from "../../components/Models";

export default function Agent() {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isSetupComplete, setIsSetupComplete] = useState(false);
    const [connection, setConnection] = useState<signalR.HubConnection | null>(null);
    const [connectionStatusText, setConnectionStatusText] = useState<string>("未连接");
    const [connectionStatus, setConnectionStatus] = useState<'success' | 'error' | 'warning' | 'info'>('warning');
    const [model, setModel] = useState(localStorage.getItem('agentModel') || 'gpt-4o');

    useEffect(() => {
        // 检查是否已经设置过
        const token = localStorage.getItem('agentToken');
        if (!token) {
            setIsModalVisible(true);
        } else {
            setIsSetupComplete(true);
        }
    }, []);

    useEffect(() => {
        if (isSetupComplete) {
            // 那么开始初始化agent，这里可以调用agent的初始化方法
            handleAgentSetup();
        }
    }, [isSetupComplete]);

    const handleAgentSetup = () => {
        // 开始连接agent
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("http://localhost:5071/api/Agent")
            .build();

        connection.start().then(() => {
            setConnectionStatus('success');
            setConnectionStatusText('已连接');
            message.success("连接成功");
            // 初始化init
            const agentToken = localStorage.getItem('agentToken');
            console.log('agentToken:', agentToken);
            connection.send("InitManager", agentToken)
              .then(() => {
                console.log("消息发送成功");
                message.success("消息发送成功");
              })
              .catch((error) => {
                console.error("消息发送失败", error);
                message.error("消息发送失败");
              });
        }).catch((error) => {
            setConnectionStatus('error');
            setConnectionStatusText('连接失败');
            // 开始重新连接
            const timer = setTimeout(() => {
                // 提示用户正在重新连接
                setConnectionStatus('warning');
                setConnectionStatusText('正在重新连接');
                handleAgentSetup();
                clearTimeout(timer);
            }, 5000);

            message.loading("正在重新连接", 5);

        });

        connection.onclose(() => {
            setConnectionStatus('info');
            setConnectionStatusText('连接已关闭');

            // 重新设置状态
            message.loading("正在重新连接", 5);
            // 开始重新连接
            const timer = setTimeout(() => {
                // 提示用户正在重新连接
                setConnectionStatus('warning');
                setConnectionStatusText('正在重新连接');
                handleAgentSetup();
                clearTimeout(timer);
            }, 5000);
        });

        setConnection(connection);
    }

    const handleSetupComplete = () => {
        setIsSetupComplete(true);
        setIsModalVisible(false);
        message.success("设置成功")
    };

    const getAgentStatus = () => {
        if (connectionStatus === 'success') {
            return '🤖'
        } else if (connectionStatus === 'error') {
            return '❌'
        } else if (connectionStatus === 'warning') {
            return '⚠️'
        } else if (connectionStatus === 'info') {
            return '💬'
        }
    }

    const getBadgeStatus = () => {
        if (connectionStatus === 'success') {
            return '#52c41a'
        } else if (connectionStatus === 'error') {
            return '#f5222d'
        } else if (connectionStatus === 'warning') {
            return '#faad14'
        } else if (connectionStatus === 'info') {
            return '#1890ff'
        }
    }


    return (
        <Flexbox style={{
            height: "100vh",
            width: "100%",
        }}>
            <AgentSetup
                isVisible={isModalVisible}
                onClose={() => setIsModalVisible(false)}
                onSetupComplete={handleSetupComplete}
            />
            <Flexbox
                horizontal
                style={{
                    height: "64px",
                    width: "100%",
                    padding: "10px",
                    marginLeft: "10px",
                }}>
                <Tooltip title={connectionStatusText} >
                    <Badge
                        color={getBadgeStatus()}
                        dot={true}>
                        <UserAvatar
                            clickable
                            avatar={getAgentStatus()}
                        />
                    </Badge>
                </Tooltip>
                <SelectModel
                    style={{
                        width: "300px",
                        // 居中
                        marginLeft: "auto",
                        marginRight: "20px",
                    }}
                    model={model}
                    onSelect={(value) => {
                        setModel(value);
                        localStorage.setItem('agentModel', value);
                    }}
                    />
            </Flexbox>
            <Divider />
            <Flexbox
                horizontal
            >
                {
                    connection && (
                        <AgentChat  
                            model={model}
                            connection={connection}
                            connectionStatus={connectionStatus}
                        />
                    )
                }
                {
                    connection && (
                        <AgentConsole
                            connection={connection}
                            connectionStatus={connectionStatus}
                        />)
                }
            </Flexbox>
        </Flexbox>
    );
}